import asyncio
import json
import threading
import time

import requests
import copy


def get_database_dict():
    with open("UPS_tasks.json", "r") as file:
        _json = file.readline()
    _dict = json.loads(_json)
    return _dict


def write_dict_to_database(_dict):
    with open("UPS_tasks.json", "w") as file:
        file.write(json.dumps(_dict))


def is_reachable(url):
    _res = requests.get(url, timeout=5)
    if _res.status_code != 200:
        return False
    return True


def to_async(task):
    tasks = []
    for url in task["urls"]:
        tasks.append(task_url_is_reachable_async(url))
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.wait(tasks))


def to_thread(task):
    for url in task["urls"]:
        _task = threading.Thread(target=task_url_is_reachable, args=(url, ))
        _task.start()


def task_url_is_reachable(url):
    if is_reachable(url["url"]):
        url["status"] = "OK"
        return True
    url["status"] = "FAILED"


async def task_url_is_reachable_async(url):
    if is_reachable(url["url"]):
        url["status"] = "OK"
        return True
    url["status"] = "FAILED"


def judge_method(task):
    _dict = {
        "async": to_async,
        "thread": to_thread
    }
    if task["ready"] == 0:
        _dict[task["driver"]](task)
        task["ready"] = 1


def main():
    while 1:
        _dict = get_database_dict()
        _dict_copy = copy.deepcopy(_dict)
        for task_id in _dict_copy["tasks"]:
            judge_method(_dict_copy["tasks"][task_id])
        time.sleep(5)
        if _dict_copy != _dict:
            write_dict_to_database(_dict_copy)
        time.sleep(1)


if __name__ == '__main__':
    main()
